<script setup lang="ts">
import { groupRequestParams, RequestParams } from "@/api/group/type";
import {
  groupList,
  addgroup,
  delgroup,
  Formgroup,
  updategroup,
  BookshelfOptions,
} from "@/api/group/index";
import { LibraryOptions } from "@/api/library/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, reactive, ref, watch } from "vue";
import useUserStore from "@/store/modules/user";
let useStore = useUserStore();
// ================================================================================
// ref
//const queryFormRef = ref(); //搜索
const ruleFormRef = ref(); //弹框表单

const ids = ref([] as number[]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
let LibOptions = ref([] as any);
const ruleForm = ref({} as any);
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
} as RequestParams);
const tableList = ref([{}] as groupRequestParams[]);

const rules = reactive({
  libraryId: [
    { required: true, message: "请选择图书馆", trigger: "change" },
    // { min: 1, max: 5, message: "请输入1到5位", trigger: "blur" },
  ],
  groupName: [
    { required: true, message: "组书架名称不能为空", trigger: "change" },
    { min: 1, max: 30, message: "组书架名称过长", trigger: "blur" },
  ],
  bookshelfIds: [
    {
      required: true,
      message: "请选择书架",
      trigger: "change",
    },
  ],
});
// 挂载
onMounted(() => {
  handleQuery();
});
// ================================================================================

/**
 * 查询
 */
const handleQuery = async () => {
  try {
    loading.value = true;
    const res = await groupList(queryParams);
    // console.log(res, "res");

    tableList.value = res.data.records;

    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    // console.error(error);
    loading.value = false; // 将 loading 的值设置为 false，以便停止加载动画
  }
};
/**
 * 重置
 */
// const resetQuery = () => {
//   queryFormRef.value.resetFields();
//   queryParams.pageNum = 1;
//   queryParams.shelfName = "";
//   queryFormRef.value.clearValidate();
//   handleQuery();
// };
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */
const bookshelfop = ref([] as any);
const bookshelfIdsref = ref();
const libraryIdref = ref();
const openDialog = async (id?: number) => {
  ruleForm.value.bookshelfIds = [];
  if (id) {
    const resss = await LibraryOptions(useStore.encryptedData);
    LibOptions.value = resss.data;

    const res = await Formgroup(id as any);
    ruleForm.value = res.data;
    const ress = await BookshelfOptions(res.data.libraryId as any);
    bookshelfop.value = ress.data;
    //  console.log(res, "addFormUser");
    title.value = "修改组书架";
  } else {
    title.value = "新增组书架";

    const res = await LibraryOptions(useStore.encryptedData);
    LibOptions.value = res.data;
    if (ruleFormRef.value) {
      ruleFormRef.value.clearValidate();
    }
  }
  dialogVisible.value = true;
};
/**
 * 关闭弹框
 */
const close = () => {
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;
};
/**
 * 处理表单提交事件
 */

const isSubmitting = ref(false);
const submit = async () => {
  if (isSubmitting.value) return; // 防止重复提交
  isSubmitting.value = true;

  try {
    const valid = await ruleFormRef.value.validate();
    if (!valid) return;

    loading.value = true;
    const userId = ruleForm.value.id;

    if (userId) {
      await updategroup(ruleForm.value);
      ElMessage.success("组书架修改成功");
    } else {
      const res = await addgroup(ruleForm.value);
      if (res.code == 200) {
        ElMessage.success("组书架新增成功");
      } else {
        ElMessage.error(res.msg);
      }
    }
    await handleQuery(); // 确保数据刷新完成
    close(); // 关闭弹窗
  } catch (error) {
    // console.error("操作失败:", error);
    // ElMessage.error("操作失败，请重试");
  } finally {
    loading.value = false;
    isSubmitting.value = false;
  }
};
/**
 * 删除
 */
const dell = (id: any) => {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    // console.log(Number(userIds), userIds);
    delgroup(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        handleQuery();
      }
    });
  });
};

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;

  handleQuery();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  handleQuery();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};

const change = async (e: any) => {
  ruleForm.value.bookshelfIds = [];
  const ress = await BookshelfOptions(e);
  bookshelfop.value = ress.data;
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate();
  }
  // console.log(ress.data);
};
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize;
};
// 计算属性，返回已排序的 Bookshelf 数据源
const sortedBookshelf = computed(() => {
  return bookshelfop.value.slice().sort((a, b) => {
    // 根据 label 的字符串大小比较
    return a.label.localeCompare(b.label);
  });
});

// 监听 formData.bookshelfList 的变化，对其进行排序
watch(
  () => ruleForm.value.bookshelfIds,
  (newValue) => {
    newValue.sort((a, b) => {
      const labelA =
        bookshelfop.value.find((item) => item.value === a)?.label || "";
      const labelB =
        bookshelfop.value.find((item) => item.value === b)?.label || "";
      return labelA.localeCompare(labelB);
    });
  }
);
</script>

<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="500px"
      append-to-body
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
        status-icon
      >
        <el-form-item label="图书馆" prop="libraryId" ref="libraryIdref">
          <el-select
            v-model="ruleForm.libraryId"
            placeholder="请选择图书馆"
            @change="change"
          >
            <el-option
              v-for="item in LibOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="书架" prop="bookshelfIds" ref="bookshelfIdsref">
          <el-select
            v-model="ruleForm.bookshelfIds"
            placeholder="请选择书架"
            multiple
          >
            <el-option
              v-for="item in sortedBookshelf"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="组书架名称" prop="groupName">
          <el-input
            v-model="ruleForm.groupName"
            placeholder="请输入组书架名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="图书馆" prop="name">
          <el-input
            v-model="queryParams.shelfName"
            placeholder="请输入图书馆名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="Search"
            >搜索</el-button
          >
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div> -->
    <el-card>
      <template #header>
        <el-button icon="Plus" type="success" @click="openDialog()"
          >新增</el-button
        >
        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="Delete"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <!--  <el-table-column type="selection" width="55" align="center" /> > -->
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column label="组书架名称" prop="groupName" align="center" />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog(row.id)"
              icon="Edit"
              >编辑</el-button
            >
            <el-button
              type="primary"
              link
              size="small"
              @click="dell(row.id)"
              icon="Delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
